<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once(APPPATH . 'controllers/admin/admin.php');

class Users extends Admin {

	const BY_ROLE = 1;
	const BY_ALPHA = 2;
	const BY_PROJECT = 3;

	function Users()
	{
		parent::Admin();

		//get the list of roles
		$this->load->model('users_roles_model');
		$this->data['roles'] = array();
		foreach($this->users_roles_model->retrieve() as $rec)
			$this->data['roles'][$rec->id] = $rec->description;
	}

	// --------------------------------------------------------------------

	function index($filter = NULL)
	{
		//if filter != NULL, get list of users using the new filters
		$this->data['user_list'] = $this->_get_users($filter);

		$this->data['admin_page_section'] = 'index';
		$this->layout->view('admin/users/index', $this->data);
	}

	// --------------------------------------------------------------------

	function create()
	{
		//create stuff
		if (form_was_submitted())
		{
			if ($this->_validate_create_update())
			{
				if ($this->users_model->create(array('login' => $this->input->post('login'), 'email' => $this->input->post('email'), 'password' => $this->input->post('pass_1'), 'first_name' => $this->input->post('first_name'), 'last_name' => $this->input->post('last_name'), 'prefer_privacy' => $this->input->post('prefer_privacy'), 'users_roles_id' => $this->input->post('role'))))
				{
					set_notice("Succesfully created the user '{$this->input->post('login')}'!", 'good');
					$this->data['user_list'] = $this->_get_users();
					redirect('admin/users');
				}
				else
				{
					if (is_mode('development'))
						set_notice("The model returned errors: " . implode(', ', $this->users_model->get_errors()), 'bad');
					else
						set_notice("There was an error creating the user.", 'bad');
				}
			}
			else
				set_notice("There was a problem with your submission.  See below.", 'bad');
		}

		$this->data['admin_page_section'] = 'create';
		$this->layout->view('admin/users/index', $this->data);
	}

	// --------------------------------------------------------------------

	function update($user_login_or_id = NULL)
	{
		//Check to ensure valid data sent
		if ($user_login_or_id === NULL)
		{
			set_notice("You must specify a user to update!");
			redirect('admin/users');
		}

		//Check to ensure the user exists.
		if ( ! $this->users_model->retrieve_single("login = '$user_login_or_id' OR id = '$user_login_or_id'"))
		{
			set_notice("The user '$user_login_or_id' does not exist!");
			redirect('admin/users');
		}

		$user_rec = $this->users_model->retrieve_single("login = '$user_login_or_id' OR id = '$user_login_or_id'");

		if (form_was_submitted())
		{
			if ($this->_validate_create_update(FALSE))
			{
				if ($this->users_model->update($user_rec->id, array('login' => $this->input->post('login'), 'email' => $this->input->post('email'), 'password' => $this->input->post('pass_1'), 'first_name' => $this->input->post('first_name'), 'last_name' => $this->input->post('last_name'), 'prefer_privacy' => $this->input->post('prefer_privacy'), 'users_roles_id' => $this->input->post('role'))))
					set_notice("Succesfully updated the user with login '$user_rec->login'!", 'good');
				else
				{
					if (is_mode('development'))
						set_notice("The model returned errors: " . implode(', ', $this->users_model->get_errors()), 'bad');
					else
						set_notice("There was an error updating the user with login '$user_rec->login'.", 'bad');
				}
			}
			else
				set_notice("There was a problem with your submission.  See below.", 'bad');
		}

		$this->data['user'] = $user_rec;

		$this->data['admin_page_section'] = 'update';
		$this->layout->view('admin/users/index', $this->data);
	}

	// --------------------------------------------------------------------

	function delete($user_login_or_id = NULL)
	{
		//Check to ensure valid data sent
		if ($user_login_or_id === NULL)
		{
			set_notice("You must specify a user to delete!");
			redirect('admin/users');
		}

		//Check to ensure the user exists.
		if ( ! $this->users_model->retrieve_single("login = '$user_login_or_id' OR id = '$user_login_or_id'"))
		{
			set_notice("The user '$user_login_or_id' does not exist!");
			redirect('admin/users');
		}

		$user_rec = $this->users_model->retrieve_single("login = '$user_login_or_id' OR id = '$user_login_or_id'");

		if (form_was_submitted('delete_' . $user_rec->id))
		{
			if ($this->input->post('confirmed'))
			{
				if ($this->users_model->update($user_rec->id, array('deactivated' => 1)))
					set_notice("Succesfully deactivated the user '$user_rec->login'.  You can undo this in the administration panel.");
				else
				{
					if (is_mode('development'))
						set_notice("The model returned errors: " . implode(', ', $this->users_model->get_errors()), 'bad');
					else
						set_notice("There was a problem deactivating the user '$user_rec->login'.");
				}
			}
			else
				set_notice("Cancelled the deletion of $user_rec->login.  User remains in system.", 'good');
			
			redirect('admin/users');
		}

		$this->data['admin_page_section'] = 'delete';
		$this->layout->view('admin/users/index', $this->data);
	}

	// --------------------------------------------------------------------

	function _get_users($filter = NULL)
	{
		$this->load->model('project_members_model');

		//if there a filter in the parameters for the function, set that to the sessoin
		if ($filter !== NULL && is_numeric($filter)&& $filter > 0 && $filter > 4)
			$this->session->set_userdata('admin_users_filter', $filter);
		//elseif there is already a filter in the session, use that
		elseif ($this->session->userdata('admin_users_filter') !== FALSE)
			$filter = $this->session->userdata('admin_users_filter');
		//else set "roles" to the default filter in the session
		else
		{
			$filter = self::BY_ROLE;
			$this->session->set_userdata('admin_users_filter', self::BY_ROLE);
		}

		$this->users_model->db->order_by('last_name DESC, first_name DESC');
		$complete_user_list = $this->users_model->retrieve(array('deactivated' => 0));

		if ($filter == self::BY_PROJECT)
		{
			//TODO: Code this!
			return array('CODE THIS!' => $complete_user_list);
		}
		elseif ($filter == self::BY_ROLE)
		{
			$out_array = array();

			foreach($complete_user_list as $user_rec)
			{
				$role_name = $this->data['roles'][$user_rec->users_roles_id];
				$out_array[$role_name][] = $user_rec;
			}
		}
		else //default to BY_ALPHA
			$out_array = array('all' => $complete_user_list);

		foreach($out_array as $section => $recs)
		{
			foreach($recs as &$rec)
			{
				$rec->role_name = $this->users_roles_model->retrieve_single($rec->users_roles_id)->description;
				$rec->num_projects = count($this->project_members_model->retrieve("`users_id` = '$rec->id'"));
			}
		}


		return $out_array;
	}

	// --------------------------------------------------------------------

	function _validate_create_update($is_create = TRUE)
	{
		if ($is_create)
		{
			$this->form_validation->set_rules('login', 'Login', 'required|alpha_dash|max_length[100]|callback__check_login_unique');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email|max_length[100]|callback__check_email_unique');
			$this->form_validation->set_rules('pass_1', 'Passwords', 'required|is_strong_pass');
			$this->form_validation->set_rules('pass_2', 'Passwords', 'required|matches[pass_1]');
		}
		else
		{
			$this->form_validation->set_rules('login', 'Login', 'required|alpha_dash|max_length[100]');
			$this->form_validation->set_rules('email', 'Email', 'required|valid_email|max_length[100]');
			$this->form_validation->set_rules('pass_1', 'Passwords', 'is_strong_pass');
			$this->form_validation->set_rules('pass_2', 'Passwords', 'matches[pass_1]');
		}

		$this->form_validation->set_rules('first_name', 'First Name', 'required|normal_punc_space|max_length[100]');
		$this->form_validation->set_rules('last_name', 'Last Name', 'required|normal_punc_space|max_lenth[100]');
		$this->form_validation->set_rules('role', 'Role', 'required|callback__role_exists');
		$this->form_validation->set_rules('prefer_privacy', 'Prefer Privacy', '');

		if ($this->form_validation->run())
			return TRUE;
		else
			return FALSE;
	}

	// --------------------------------------------------------------------

	/*
	 * Form Callbacks
	 */

	// --------------------------------------------------------------------

	function _role_exists($str)
	{
		if ( ! in_array($str, array_keys($this->data['roles'])))
		{
			$this->form_validation->set_message('_role_exists', "The role you are attempting to be added to does not exist!");
			return FALSE;
		}
		else
			return TRUE;
	}

	// --------------------------------------------------------------------

	function _check_login_unique($str)
	{
		if (count($this->users_model->retrieve(array('login' => $str))))
		{
			$this->form_validation->set_message('_check_login_unique', "The login you entered already exists!");
			return FALSE;
		}
		else
			return TRUE;
	}

	// --------------------------------------------------------------------

	function _check_email_unique($str)
	{
		if (count($this->users_model->retrieve(array('email' => $str))))
		{
			$this->form_validation->set_message('_check_email_unique', "The email you entered already exists!");
			return FALSE;
		}
		else
			return TRUE;
	}
}

/* End of file users.php */
/* Location: ./system/application/controllers/admin/users.php */